package com.shut.vehicle.dao.handler;

import com.alibaba.fastjson2.JSONArray;
import com.aliyun.core.utils.StringUtils;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author 卢斌
 */
@MappedJdbcTypes({JdbcType.VARCHAR, JdbcType.LONGVARCHAR})
@MappedTypes({JSONArray.class})
public class JsonArrayHandler implements TypeHandler<JSONArray> {
    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, JSONArray objects, JdbcType jdbcType) throws SQLException {
        if (objects == null) {
            preparedStatement.setString(i, new JSONArray().toJSONString());
        } else {
            preparedStatement.setString(i, objects.toJSONString());
        }
    }

    @Override
    public JSONArray getResult(ResultSet resultSet, String s) throws SQLException {
        String result = resultSet.getString(s);
        if (StringUtils.isBlank(result)) {
            return new JSONArray();
        }
        return JSONArray.parseArray(result);
    }

    @Override
    public JSONArray getResult(ResultSet resultSet, int i) throws SQLException {
        String result = resultSet.getString(i);
        if (StringUtils.isBlank(result)) {
            return new JSONArray();
        }
        return JSONArray.parseArray(result);
    }

    @Override
    public JSONArray getResult(CallableStatement callableStatement, int i) throws SQLException {
        String result = callableStatement.getString(i);
        if (StringUtils.isBlank(result)) {
            return new JSONArray();
        }
        return JSONArray.parseArray(result);
    }
}
